#include "readypage.h"
#include "director.h"
#include "ui_readypage.h"
#include <QDebug>
#include <QJsonObject>
#include <QMessageBox>

ReadyPage::ReadyPage(QWidget *parent)
    : AbstractPage(parent), ui(new Ui::ReadyPage) {
  ui->setupUi(this);
}

ReadyPage::~ReadyPage() { delete ui; }

void ReadyPage::updated() {
  ui->roomLablel->setText(Director::instance()->room);
  ui->currentLabel->setText(
      QString::number(Director::instance()->users.size()));
  if (Director::instance()->m_created) {
    ui->pushButton_2->show();
  } else
    ui->pushButton_2->hide();
}

void ReadyPage::leave() {}

void ReadyPage::notify(const QJsonObject &obj) {
  qDebug() << __func__ << __LINE__ << obj;
  ui->currentLabel->setText(
      QString::number(Director::instance()->users.size()));

  if (obj.contains("code") && obj.value("code").toInt() != 0) {
    QMessageBox::information(this, "提示", obj.value("msg").toString());
  }

  if (obj.value("type").toString() == "notify" &&
      obj.value("event").toString() == "play") {
    Director::instance()->backward();
  }
}

// begin game
void ReadyPage::on_pushButton_2_clicked() {
  int subsist = ui->spinBox_2->value();
  if (subsist < Director::instance()->users.size()) {
    Director::instance()->sendPlay(ui->spinBox->value(),
                                   ui->spinBox_2->value());
  } else {
    QMessageBox::information(this, "提示", "当前人数不够，不能开始");
  }
}

void ReadyPage::on_pushButton_clicked() {
  if (QMessageBox::Ok ==
      QMessageBox::information(this, "确认", "请问你确定是否离开",
                               QMessageBox::Ok | QMessageBox::Cancel)) {
    Director::instance()->forward();
    Director::instance()->sendLeave();
  }
}
